package com.chudy.visual.server.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.chudy.visual.server.model.ScContentDelivery;
import com.chudy.visual.server.pojo.push.Contentlist;
import com.chudy.visual.server.push.VisualPushUtils;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;

public class ScContentService {
	/**
	 */
	private ScContentDelivery dao = new ScContentDelivery().dao();
	public Page<ScContentDelivery> paginate(int pageNumber, int pageSize) {
		return dao.paginate(pageNumber, pageSize, "select *", "from sc_device order by id asc");
	}
	public ScContentDelivery findById(String id) {
		return dao.findById(id);
	}
	
	public ScContentDelivery findByDeviceId(String deviceid) {
		return dao.findFirst("SELECT * FROM `sc_content_delivery` WHERE deviceid = ? ORDER BY delivery_time DESC", deviceid);
	}
	public ScContentDelivery findByDefault() {
		return dao.findFirst("SELECT * FROM `sc_content_delivery` WHERE deviceid = 'default' ORDER BY delivery_time DESC");
	}

	public boolean saveContentDelivery(ScContentDelivery contentDelivery) {
		ScContentDelivery old = findByDeviceId(contentDelivery.getDeviceid());
		if(null!=old){
			old.setContentData(contentDelivery.getContentData());
			old.setDeliveryTime(DateUtil.date());
			return old.update();
		}else{
			old = contentDelivery;
			old.setContentId(String.valueOf(IdUtil.getSnowflakeNextId()));
			old.setDeliveryTime(DateUtil.date());
			old.setTenantId(PropKit.getLong("tenant.id"));
			return old.save();
		}
	}

	public Ret pushContent(ScContentDelivery contentDelivery) {
		Ret data = new Ret();
		data.put("contentlist", JSONObject.parseArray(contentDelivery.getContentData(), Contentlist.class));
		data.put("pushtype","screens");
		saveContentDelivery(contentDelivery);
		VisualPushUtils.push(contentDelivery.getDeviceid(), JSONUtil.toJsonStr(data));
		return data;
	}

}
